package com.cht.commonUtil.webInit;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import com.cht.commonUtil.enums.QuartzJobStatus;
import com.cht.commonUtil.quartz.QuartzChkinJob;
import com.cht.commonUtil.widgets.Widgets;

public class SP implements ServletContextListener {

	static public String APftpId;
	static public String APftpIP;
	static public String APftpPath;
	static public String APftpPwd;
	static public boolean isDepApplyNeed;
	static public boolean isPerformHTTPD;
	static public boolean isReloadNeed;
	static public boolean isTestNeedConfirm;
	static public boolean isNeedQAqualified;
	static public boolean isBindingRequirementOnChkIn;
	static public boolean isBindingRequirementOnDeliver;
	
	static public int svnCount;
	static public String APsvnId;
	static public String APsvnIP;
	static public String APsvnPath;
	static public String APsvnPwd;
	static public String postBuildAPserverHost;
	static public String dateFormat;
	static public String DBcodeSet;	
	static public String jenkinsPwd;
	static public String jenkinsId;
	static public String jenkinsUrl;
	static public String JNDINAME="java:jboss/datasources/DPS";
    static public String mailLocale;
    static public String mailServer;
	static public String mailServerIP;
	static public String UIcodeSet;	

	
	@Override
	public void contextInitialized(ServletContextEvent ctx) {
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = Widgets.getConn();
			//重新恢復排程
			Scheduler sched = new StdSchedulerFactory("myquartz.properties").getScheduler();
			ctx.getServletContext().setAttribute("sched",sched);
			String sql = "SELECT quartzId,cronString,subsysId FROM quartzjob WHERE status=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, QuartzJobStatus.ACTIVATED );
			rs = ps.executeQuery();
			while( rs.next() ) {
				String subsysId = rs.getString("subsysId");
				long quartzId = rs.getLong("quartzId");
				String cronString = rs.getString("cronString");
				List<String> svnAP = Widgets.getSVN4SubsysConnInfo(subsysId, 4);	//SVN AP OL的連線資訊
				JobDataMap jdm = new JobDataMap();
				jdm.put("subsysId", subsysId);
				jdm.put("svnUrl", svnAP.get(0));
				jdm.put("svnPath", "trunk");
				
				JobDetail jd = newJob(QuartzChkinJob.class).withIdentity( String.valueOf( quartzId ), subsysId ).setJobData(jdm).build();
				Trigger trigger = newTrigger().forJob(String.valueOf( quartzId ), subsysId).withIdentity(String.valueOf( quartzId ), subsysId).withSchedule(cronSchedule( cronString )).startNow().build();
				boolean isExist = sched.checkExists(jd.getKey());
				if ( !isExist ) {
					Date fireTime = sched.scheduleJob(jd, trigger);
					System.out.println(jd.getKey().getGroup()+", "+jd.getKey().getName()+" ,下次執行時間："+fireTime);
				}
			}
			sched.start();
			if (rs != null) { rs.close(); }
			if (ps != null) { ps.close(); }
			
			//以下為產生系統變數
			sql = "SELECT paraName,paraVal FROM configparameter";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				if( "ftpId".equalsIgnoreCase( rs.getString("paraName") ) ) { APftpId = rs.getString("paraVal"); }
				if( "ftpIP".equalsIgnoreCase( rs.getString("paraName") ) ) { APftpIP = rs.getString("paraVal"); }
				if( "ftpPath".equalsIgnoreCase( rs.getString("paraName") ) ) { APftpPath = rs.getString("paraVal"); }
				if( "ftpPwd".equalsIgnoreCase( rs.getString("paraName") ) ) { APftpPwd = rs.getString("paraVal"); }
				
				if( "isDepApplyNeed".equalsIgnoreCase( rs.getString("paraName") ) ) { isDepApplyNeed = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isPerformHTTPD".equalsIgnoreCase( rs.getString("paraName") ) ) { isPerformHTTPD = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isReloadNeed".equalsIgnoreCase( rs.getString("paraName") ) ) { isReloadNeed = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isTestNeedConfirm".equalsIgnoreCase( rs.getString("paraName") ) ) { isTestNeedConfirm = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isNeedQAqualified".equalsIgnoreCase( rs.getString("paraName") ) ) { isNeedQAqualified = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isBindingRequirementOnChkIn".equalsIgnoreCase( rs.getString("paraName") ) ) { isBindingRequirementOnChkIn = Boolean.parseBoolean( rs.getString("paraVal")); }
				if( "isBindingRequirementOnDeliver".equalsIgnoreCase( rs.getString("paraName") ) ) { isBindingRequirementOnDeliver = Boolean.parseBoolean( rs.getString("paraVal")); }
				
				if( "svnCount".equalsIgnoreCase( rs.getString("paraName") ) ) { svnCount = Integer.parseInt( rs.getString("paraVal") ); }
				if( "svnId".equalsIgnoreCase( rs.getString("paraName") ) ) { APsvnId = rs.getString("paraVal"); }
				if( "svnIP".equalsIgnoreCase( rs.getString("paraName") ) ) { APsvnIP = rs.getString("paraVal"); }
				if( "svnPath".equalsIgnoreCase( rs.getString("paraName") ) ) { APsvnPath = rs.getString("paraVal"); }
				if( "svnPwd".equalsIgnoreCase( rs.getString("paraName") ) ) { APsvnPwd = rs.getString("paraVal"); }
				if( "postBuildAPserverHost".equalsIgnoreCase( rs.getString("paraName") ) ) { postBuildAPserverHost = rs.getString("paraVal"); }
				if( "dateFormat".equalsIgnoreCase( rs.getString("paraName") ) ) { dateFormat = rs.getString("paraVal"); }
				if( "DBcodeSet".equalsIgnoreCase( rs.getString("paraName") ) ) { DBcodeSet = rs.getString("paraVal"); }
				
				if( "jenkinsPwd".equalsIgnoreCase( rs.getString("paraName") ) ) { jenkinsPwd = rs.getString("paraVal"); }
				if( "jenkinsId".equalsIgnoreCase( rs.getString("paraName") ) ) { jenkinsId = rs.getString("paraVal"); }
				if( "jenkinsUrl".equalsIgnoreCase( rs.getString("paraName") ) ) { jenkinsUrl = rs.getString("paraVal"); }
				
				if( "mailLocale".equalsIgnoreCase( rs.getString("paraName") ) ) { mailLocale = rs.getString("paraVal"); }
				if( "mailServer".equalsIgnoreCase( rs.getString("paraName") ) ) { mailServer = rs.getString("paraVal"); }
				if( "mailServerIP".equalsIgnoreCase( rs.getString("paraName") ) ) { mailServerIP = rs.getString("paraVal"); }
				
				if( "UIcodeSet".equalsIgnoreCase( rs.getString("paraName") ) ) { UIcodeSet = rs.getString("paraVal"); }
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) { rs.close(); }
				if (ps != null) { ps.close(); }
				if (conn != null) { conn.close(); }
			} catch (Exception e1) { e1.printStackTrace(); }
		}
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent ctx) {
		Scheduler sched = (Scheduler)ctx.getServletContext().getAttribute("sched");
		Scheduler sched2 = (Scheduler)ctx.getServletContext().getAttribute("aaaa");
		
		try {
			for (String groupName : sched.getJobGroupNames()) {

				for (JobKey jobKey : sched.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

					String jobName = jobKey.getName();
					String jobGroup = jobKey.getGroup();

					List<Trigger> triggers = (List<Trigger>) sched.getTriggersOfJob(jobKey);
					Date nextFireTime = triggers.get(0).getNextFireTime();

					System.out.println("[jobName] : " + jobName
							+ " [groupName] : " + jobGroup + " - "
							+ nextFireTime);

				}
			}
		} catch (SchedulerException e1) { e1.printStackTrace(); }
		
		System.out.println((sched==null)+"欲結束Jboss"+(sched2==null));
		try {
			sched.shutdown();
		} catch (SchedulerException e) { e.printStackTrace(); }
	}

}
